package com.mvity.framework.common.utils;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

import com.mvity.framework.common.base.BaseUtil;

/**
 * memcached 客户端工具类
 * 
 * @ClassName MemCachedUtil
 * @Description
 * @author 栗相楠
 * @date 2012-4-5 下午4:17:52
 * 
 */
public final class MemCachedUtil extends BaseUtil {

	private static final long serialVersionUID = 6244209102104280840L;

	/**
	 * 此处模拟一个内存 memecached
	 */

	static ConcurrentHashMap<String, Serializable> cacheMap = new ConcurrentHashMap<String, Serializable>();

	/**
	 * 放入缓存
	 * 
	 * @param key
	 * @param value
	 */
	public static void put(String key, Serializable value) {
		cacheMap.put(key, value);
	}

	/**
	 * 移除缓存
	 * 
	 * @param key
	 */
	public static void remove(String key) {
		cacheMap.remove(key);
	}

	/**
	 * 获取缓存对象
	 * 
	 * @param clazz
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends Serializable> T get(Class<T> clazz, String key) {

		return (T) cacheMap.get(key);
	}

	/**
	 * 替换缓存内容
	 * 
	 * @param key
	 * @param value
	 */
	public static void replace(String key, Serializable value) {
		cacheMap.replace(key, value);
	}

	/**
	 * 添加到缓存
	 * 
	 * @param key
	 * @param value
	 */
	public static void add(String key, Serializable value) {
		if (cacheMap.containsKey(key)) {
			replace(key, value);
		} else {
			put(key, value);
		}
	}
}
